package com.jz.community.basecomm.task;

import android.app.Activity;

import com.jz.community.basecomm.bean.LoginBaseInfo;
import com.jz.community.basecomm.bean.UserInfo;
import com.jz.community.basecomm.bean.WeChatUserInfo;
import com.jz.community.basecomm.constant.Constant;
import com.jz.community.basecomm.net.OkHttpUtil;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.JsonUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.commview.view.widget.ProgressDialogManager;

import java.util.HashMap;

/**
 * Created by Tony.Fan on 2018/3/21 17:47
 * 获取微信登录用户信息
 */
public class GetLoginWeChatUserTask extends RxTask<String, Integer, WeChatUserInfo> {

    private Activity activity;
    private ITaskCallbackListener taskListener;

    public GetLoginWeChatUserTask(Activity activity,
                                  ITaskCallbackListener taskListener) {
        super(activity);
        this.activity = activity;
        this.taskListener = taskListener;
    }

    @Override
    protected WeChatUserInfo doInBackground(String... params) {
        // 执行请求
        String result = OkHttpUtil.get(Constant.HTTP_WECHAT_URL_BASE_HEAD, getParam());
        WeChatUserInfo info = null;
        if (!Preconditions.isNullOrEmpty(result)) {
            info = JsonUtils.parseObject(result, WeChatUserInfo.class);
            saveUserInfo(info);
        }
        return info;
    }

    @Override
    protected void onPostExecute(WeChatUserInfo result) {
        // 执行结果回调函数
        taskListener.doTaskComplete(result);
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
    }

    /**
     * 获取请求所需的参数
     *
     * @param
     * @return
     */
    private HashMap<String, Object> getParam() {

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("access_token", BaseSpUtils.getInstance().getWeChatToken(activity));
        hashMap.put("openid", BaseSpUtils.getInstance().getOpenid(activity));
        return hashMap;
    }

    /**
     * @param weChatUserInfo
     */
    private void saveUserInfo(WeChatUserInfo weChatUserInfo) {
        LoginBaseInfo loginBaseInfo = new LoginBaseInfo();
        loginBaseInfo.setName(weChatUserInfo.getNickname());
        loginBaseInfo.setIcon(weChatUserInfo.getHeadimgurl());
        BaseSpUtils.getInstance().setNickname(activity,weChatUserInfo.getNickname());
        BaseSpUtils.getInstance().setUserBaseInfo(activity,loginBaseInfo);
    }

}